﻿using System.Linq;
using System.IO;
using System.Xml.Linq;
using System.Windows;
using DevExpress.Xpf.Core;

namespace SQLQuery.Common
{
    public class XmlHelper
    {
        private readonly string _path;
        private static XmlHelper _instance;
        private XmlHelper()
        {
            _path = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + "QueryConfig.xml";
            VerityXml();
        }

        public static XmlHelper Instance
        {
            get { return _instance ?? (_instance = new XmlHelper()); }
        }

        public string ThemeInfo
        {
            get { return GetTheme(); }
            set { SetTheme(value); }
        }
        /// <summary>
        /// 给窗体设置皮肤
        /// </summary>
        /// <param name="win"></param>
        public void SetTheme(DependencyObject win)
        {
            string themeName = GetTheme();
            if (themeName != string.Empty)
            {
                ThemeManager.SetThemeName(win, themeName);
            }
        }

        public string FontName { get; set; }

        private void VerityXml()
        {
            if (!File.Exists(_path))
            {
                XElement root = new XElement("Query");

                XDocument document = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    root);
                document.Save(_path);
            }
        }

        private string GetTheme()
        {
            XElement element = XElement.Load(_path);
            XElement xe = element.Elements().FirstOrDefault(o => o.Name.LocalName == "Theme");
            if (xe == null)
            {
                return string.Empty;
            }
            return xe.Value;
        }
        private void SetTheme(string theme)
        {
            if (string.IsNullOrEmpty(theme))
                return;
            XElement element = XElement.Load(_path);
            XElement xe = element.Elements().FirstOrDefault(o => o.Name.LocalName == "Theme");
            if (xe == null)
            {
                xe = new XElement("Theme");
                element.Add(xe);
            }
            xe.Value = theme;
            element.Save(_path);
        }

        
    }
}
